package com.nc.mem.serial.graph.cust;

import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.SortedSet;

import com.nc.mem.serial.graph.Representation;
import com.nc.mem.serial.graph.asm.GraphSerializerFactory;


public final class CollectionHolder<T> implements Iterable<T> {

	Collection<T> src;

	final byte flags;

	public CollectionHolder(final Collection<T> src, final boolean onlyPayLoad) {
		super();
		this.src = src;
		this.flags = (byte) (onlyPayLoad ? 1 : 0);
	}

	public void clear() {
		src = null;
	}

	public Class<?> collectionClass() {
		return src.getClass();
	}

	public boolean isOnlyPayload() {
		return flags == 1;
	}

	@Override
	public Iterator<T> iterator() {
		return src.iterator();
	}

	public int size() {
		return src.size();
	}

	public void writeKindAndSize(final ByteBuffer dest) {
		final Collection<T> col = src;
		final Comparator<?> c = col instanceof SortedSet ? ((SortedSet<?>) col).comparator() : null;
		final long s = col.size() << 1 | (c != null ? 1 : 0);

		Representation.writeLong(dest, s);

		if (c != null) {
			GraphSerializerFactory.serializer(c.getClass()).write(dest, c);
			Representation.writeLong(dest, s);
		}

	}

}
